import axios from 'axios'
import store from '@/store/index.js'
import { ElLoading } from 'element-plus'
import { ElMessage } from 'element-plus'

let instance = axios.create({
    baseURL: ""
})
let loadingInstance = null
let loadingOption = {
    lock: true,
    text: '数据正在加载中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.2)'
}
let needLoadingRequestCount = 0
// 添加请求拦截器
instance.interceptors.request.use(
    config => {  // 发送请求之前做些什么
        config.headers["Access-Token"] = store.getToken()
        needLoadingRequestCount++
        loadingInstance = ElLoading.service(loadingOption)
        return config
    },
    error => {   // 对请求错误做些什么
        return Promise.reject(error)
    }
)

// 添加响应拦截器
instance.interceptors.response.use(
    response => { // 对响应数据做点什么
        needLoadingRequestCount--
        if (needLoadingRequestCount <= 0) {
            loadingInstance.close()
        }
        if (response.data.code !== 'Success') {
            ElMessage.error(response.data.msg || "请求错误！")
        }
        return response.data
    },
    error => { // 对响应错误做点什么 
        if (error.response.status == "400") {
            ElMessage.error(error?.response?.data.msg || "请求错误！")
        }
        if (error.response.status == "401") {
            let href = window.location.href
            let index = href.indexOf("token=")
            if (index > 0) {
                href = href.substr(0, index)
            }
            if(error.response.data.sso_url) {
                // cck-op
                if (error.response.data.sso_url.indexOf('test') !== -1) {
                    window.location.href = error.response.data.sso_url.split('currentInfo')[0] + "pages/index.html?next=" + href
                } else {
                    window.location.href = error.response.data.sso_url.split('com/')[0] + "com/pages/index.html?next=" + href
                }
            } else if(error.response.data.data.sso_url) {
                // eks-op
                if (error.response.data.data.sso_url.indexOf('test') !== -1) {
                    window.location.href = error.response.data.data.sso_url.split('currentInfo')[0] + "pages/index.html?next=" + href
                } else {
                    window.location.href = error.response.data.data.sso_url.split('com/')[0] + "com/pages/index.html?next=" + href
                }
            }
            

            // console.log(error.response.data.sso_url.split('com/')[0] + "com/pages/index.html?next=" + href)
        }
        needLoadingRequestCount--
        if (needLoadingRequestCount <= 0) {
            loadingInstance.close()
        }
        return Promise.reject(error)
    }
)

export default instance